<?php

namespace App\Http\Controllers\App;

use App\Helpers\FileUpload;
use App\Http\Controllers\Controller;
use App\Http\Requests\EditProductRequest;
use App\Http\Requests\ProductRequest;
use App\Http\Resources\OrderResource;
use App\Models\Cart;
use App\Models\Merchant;
use App\Models\Order;
use App\Models\Product;
use App\Models\ProductImage;
use App\Models\SUsers;
use App\Rules\NumericRule;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Yansongda\Pay\Log;

class MerchantController extends Controller
{
    /**
     * 商户添加商品
     * @param ProductRequest $request
     * @return array
     * @throws \Throwable
     */
    public function addProduct(ProductRequest $request){
        $user = SUsers::where('openid',$request->get('openid'))->first();
        if (!$user){
            return [
                'result' => 'failed',
                'message' => '请先登录！'
            ];
        }
        if ($user->merchant_id === -1){
            return [
                'result' => 'failed',
                'message' => '您没有权限操作，请先注册成为商户！'
            ];
        }
        //商家商品上传数限制
//        $merchant = Merchant::where('user_id',$user->id)->first();
//        $product_amount = Product::where('merchant_id',$merchant->id)->count();
//        if ($product_amount >= $merchant->amount){
//            return [
//                'result' => 'failed',
//                'message' => '请先申请增加商户可添加的商品数！'
//            ];
//        }

        $product = new Product;
        $product->cate_id = $request->get('cate_id');
        $product->name = $request->get('name');
        $product->detail = $request->get('detail');
        $product->cost_price = $request->get('cost_price');
        $product->price = $request->get('price');
        $product->original_price = $request->get('original_price');
        $product->stock = $request->get('stock')?$request->get('stock'):-1;
        $product->activity_type = $request->get('type')?$request->get('type'):1;
        $product->merchant_id = $user->merchant_id;
        $product->domestic = $request->get('domestic', 1);

        $product->saveOrFail();
        return [
            'result' => 'success',
            'message' => '商品上传成功！',
            'data' => $product
        ];

    }

    /**
     * 商户上传商品图片
     * @param Request $request
     * @return array
     * @throws \Throwable
     */
    public function uploadProductImage(Request $request){
        $validator = Validator::make($request->all(), [
            'id' => ['required','numeric'],
            'sort' => ['numeric'],
            'type' => ['required',new NumericRule],
            'image' => "file"
        ]);

        if ($validator->fails()) {
            return [
                "result" => "failed",
                "message" => $validator->errors()
            ];
        }
        $count = $request->get('sort');
        if (!$count){
            $count = ProductImage::where('product_id',$request->get('id'))->where('type',$request->get('type'))->count() + 1;
        }


        $upload = new FileUpload();
        $path = $upload->productImageUpload($request,$request->get('type'));
        $image = new ProductImage();
        $image->product_id = $request->get('id');
        $image->type = $request->get('type');
        $image->path = $path;
        $image->sort_number = $count;
        $image->saveOrFail();
        return [
            "result" => "success",
            "data" => $image
        ];

    }


    /**
     * 商户商品列表
     * @param Request $request
     * @return array
     */
    public function merchantProductList(Request $request){
        $validator = Validator::make($request->all(), [
            'openid' => ['required'],
        ]);

        if ($validator->fails()) {
            return [
                "result" => "failed",
                "message" => $validator->errors()
            ];
        }
        $user = SUsers::where('openid',$request->get('openid'))->first();
        if ($user->merchant_id == -1){
            return[
                "result" => "failed",
                "message" => "商户不存在！"
            ];
        }
        $list = Product::where('merchant_id',$user->merchant_id)->orderBy('shelves','desc')->orderBy('updated_at','desc')->paginate(10);

        return[
            "result" => "success",
            "data" => $list
        ];


    }

    /**
     * 商户商品详情
     * @param Request $request
     * @return array|string[]
     */
    public function merchantProductDetail(Request $request){
        $validator = Validator::make($request->all(), [
            'openid' => ['required'],
            'product_id' => ['required'],
        ]);

        if ($validator->fails()) {
            return [
                "result" => "failed",
                "message" => $validator->errors()
            ];
        }
        $user = SUsers::where('openid',$request->get('openid'))->first();
        if ($user->merchant_id == -1){
            return[
                "result" => "failed",
                "message" => "商户不存在！"
            ];
        }

        $product_id = $request->get('product_id');
        $product = Product::findOrFail($product_id);
        $main_img = ProductImage::where('product_id',$product_id)->where('type',1)->get();
        $detail_img = ProductImage::where('product_id',$product_id)->where('type',2)->get();
        $activity_img = ProductImage::where('product_id',$product_id)->where('type',3)->get();

        $data = [
            "product" => $product,
            "main_img" => $main_img,
            "detail_img" => $detail_img,
            "activity_img" => $activity_img,
            "buy_record" => ''
        ];

        return[
            "result" => "success",
            "data" => $data
        ];

    }

    /**
     * 商户编辑商品信息
     * @param EditProductRequest $request
     * @return string[]
     */
    public function editMerchantProduct(EditProductRequest $request){
        $user = SUsers::where('openid',$request->get('openid'))->first();
        if ($user->merchant_id == -1){
            return[
                "result" => "failed",
                "message" => "商户不存在！"
            ];
        }
        $product = Product::findOrFail($request->get('product_id'));

        $product->cate_id = isset($request['cate_id'])?$request->get('cate_id'):$product->cate_id;
        $product->name = isset($request['name'])?$request->get('name'):$product->name;
        $product->detail = isset($request['detail'])?$request->get('detail'):$product->detail;
        $product->cost_price = isset($request['cost_price'])?$request->get('cost_price'):$product->cost_price;
        $product->price = isset($request['price'])?$request->get('price'):$product->price;
        $product->original_price = isset($request['original_price'])?$request->get('original_price'):$product->original_price;
        $product->stock = isset($request['stock'])?$request->get('stock'):$product->stock;
        $product->activity_type = isset($request['type'])?$request->get('type'):$product->activity_type;
        $product->domestic = $request->get('domestic', 1);
        $product->saveOrFail();
        return[
            "result" => "success",
            "message" => "更新成功！"
        ];

    }


    /**
     * 商户删除商品图片
     * @param Request $request
     * @return array|string[]
     */
    public function deleteMerchantProductImage(Request $request){
        $validator = Validator::make($request->all(), [
            'openid' => ['required'],
            'image_id' => ['required'],
        ]);

        if ($validator->fails()) {
            return [
                "result" => "failed",
                "message" => $validator->errors()
            ];
        }
        $user = getUser($request);
        if ($user->merchant_id == -1){
            return[
                "result" => "failed",
                "message" => "商户不存在！"
            ];
        }
        $image = ProductImage::findOrFail($request->get('image_id'));
        if (Storage::disk('public')->delete($image->path)){
            $image->delete();
            return [
                "result"=>"success",
                "message"=>"图片删除成功"
            ];
        }
        return [
            "result" => "failed",
            "message" => "删除失败，请联系管理员"
        ];
    }


    /**
     * 商户删除商品
     * @param Request $request
     * @return array|string[]
     */
    public function deleteMerchantProduct(Request $request){
        $validator = Validator::make($request->all(), [
            'openid' => ['required'],
            'product_id' => ['required'],
        ]);

        if ($validator->fails()) {
            return [
                "result" => "failed",
                "message" => $validator->errors()
            ];
        }
        $user = getUser($request);
        if ($user->merchant_id == -1){
            return[
                "result" => "failed",
                "message" => "商户不存在！"
            ];
        }

        $product = Product::findOrFail($request->get('product_id'));
        if ($product->delete()){
            return [
                "result"=>"success",
                "message"=>"删除成功"
            ];
        }
        return[
            "result" => "failed",
            "message" => "删除失败，请联系管理员！"
        ];

    }

    /**
     * 商品上下架
     * @param Request $request
     * @return array|string[]
     */
    public function putOnShelves(Request $request){
        $validator = Validator::make($request->all(), [
            'openid' => ['required'],
            'product_id' => ['required'],
        ]);

        if ($validator->fails()) {
            return [
                "result" => "failed",
                "message" => $validator->errors()
            ];
        }
        $user = getUser($request);
        if ($user->merchant_id == -1){
            return[
                "result" => "failed",
                "message" => "商户不存在！"
            ];
        }

        $product = Product::findOrFail($request->get('product_id'));
        if (!$product->verify && $product->shelves){
            return[
                "result" => "failed",
                "message" => "商品未经过审核！"
            ];
        }


        DB::transaction(function ()use ($product){
            $product->shelves = !$product->shelves;
            $product->saveOrFail();
            if ($product['shelves'] == 0){
                Cart::where('product_id',$product['id'])->delete();
            }
        },5);


        return [
            "result"=>"success",
            "message"=>"上架成功"
        ];

    }

    /**
     * 商家订单列表
     * @param Request $request
     * @return array|string[]
     */
    public function getOrderList(Request $request){
        $validator = Validator::make($request->all(), [
            'openid' => ['required'],
            'status_code' => ['required',new NumericRule],
        ]);

        if ($validator->fails()) {
            return [
                "result" => "failed",
                "message" => $validator->errors()
            ];
        }
        $user = getUser($request);
        if ($user->merchant_id == -1){
            return[
                "result" => "failed",
                "message" => "商户不存在！"
            ];
        }
        $orders = Order::withTrashed()
            ->where('merchant_id',$user['merchant_id'])
            ->when($request->get('status_code'),function ($query)use($request){
            return $query->where('status',$request->get('status_code'));
            })
            ->orderBy('created_at','desc')
            ->paginate(10);

        Log::info($orders);
        return [
            'result'=>'success',
            'data'=>[
                'data'=>OrderResource::collection($orders),
                'last_page'=>$orders->lastPage()
            ]
        ];

    }

    /**
     * 统计订单数量
     * @param Request $request
     * @return array|string[]
     */
    public function getOrderAmount(Request $request){
        $validator = Validator::make($request->all(), [
            'openid' => ['required'],
        ]);

        if ($validator->fails()) {
            return [
                "result" => "failed",
                "message" => $validator->errors()
            ];
        }
        $user = getUser($request);
        if ($user->merchant_id == -1){
            return[
                "result" => "failed",
                "message" => "商户不存在！"
            ];
        }

        $ready_send = Order::where('merchant_id',$user['merchant_id'])->where('status',2)->count();
        return [
            'result' => 'success',
            'data' => [
                'ready_send' => $ready_send
            ]
        ];

    }


    /**
     * 发货登记
     * @param Request $request
     * @return array|string[]
     */
    public function sendProducts(Request $request){
        $validator = Validator::make($request->all(), [
            'openid' => ['required'],
            'order_id' => ['required','numeric'],
            'tracking_type' => ['required','max:100'],
            'tracking_number' => ['required','max:200'],
        ]);

        if ($validator->fails()) {
            return [
                "result" => "failed",
                "message" => $validator->errors()
            ];
        }
        $user = getUser($request);
        if ($user->merchant_id == -1){
            return[
                "result" => "failed",
                "message" => "商户不存在！"
            ];
        }

        $order = Order::where('id',$request->get('order_id'))->withTrashed()->first();
        if ($order['status'] != 2){
            return[
                "result" => "failed",
                "message" => "订单状态错误，请联系管理员！"
            ];
        }
        $order['tracking_number'] = $request->get('tracking_number');
        $order['tracking_type'] = $request->get('tracking_type');
        $order['status'] = 3;
        $order->saveOrFail();
        return [
            'result' => 'success',
            'message' => "发货登记成功"
        ];

    }


    public function journalAccount(Request $request){
        $validator = Validator::make($request->all(), [
            'openid' => ['required']
        ]);

        if ($validator->fails()) {
            return [
                "result" => "failed",
                "message" => $validator->errors()
            ];
        }
        $user = getUser($request);
        if ($user->merchant_id == -1){
            return[
                "result" => "failed",
                "message" => "商户不存在！"
            ];
        }



    }


}
